/* 
 * A UDP server that gets a packet, delays for delay, and echos it back to the sender
 */ 

#include "networking.h"
/*
 * convenient global variables
 */
int                       debug=0;
uint16_t                  serverport=8000;
int                       delay = 1;

static void
parse_args(int argc, char** argv) 
{
  int n = 1;
  while (n < argc) {
    if (strcmp(argv[n], "-delay") == 0) {
      delay = atoi(argv[++n]);
    } else if (strcmp(argv[n], "-debug") == 0) {
      debug = 1;
    } else if (strcmp(argv[n], "-port") == 0) {
      serverport = atoi(argv[++n]);
    } else
      err_quit("usage: %s [-port <port>] [-debug] [-delay second]", argv[0]);
    n++;
  }
}

int
main(int argc, char **argv)
{
  int	                  sockfd;
  struct sockaddr_in	  serveraddr, clientaddr;

  parse_args(argc, argv);

  if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    err_quit("Cannot create UDP socket!");
  }
  
  bzero(&serveraddr, sizeof(serveraddr));
  serveraddr.sin_family      = AF_INET;
  serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
  serveraddr.sin_port        = htons(serverport);

  bind(sockfd, (SA *) &serveraddr, sizeof(serveraddr));

  int		n;
  socklen_t	len;
  char		mesg[MAXBUF];
  
  for ( ; ; ) {
    len = sizeof(clientaddr);
    n = recvfrom(sockfd, mesg, MAXBUF, 0, (SA *)&clientaddr, &len);
    sleep(delay);
    sendto(sockfd, mesg, n, 0, (const SA*)&clientaddr, len);
  }
}
